﻿
namespace BJYJ_Admin.Core.DataBaseLog;

public class DatabaseLoggingWriter : IDatabaseLoggingWriter
{
    public readonly ISqlSugarClient _db;
    public DatabaseLoggingWriter(ISqlSugarClient db)
    {
        _db = db;
    }

    public async Task WriteAsync(LogMessage logMsg, bool flush)
    {
        try
        {
            var jsonStr = logMsg.Context?.Get("loggingMonitor")?.ToString();
            if (string.IsNullOrWhiteSpace(jsonStr))
            {
                // 未找到监控日志信息
            }
            var loggingMonitor = (JObject)JsonConvert.DeserializeObject(jsonStr);
            var str = loggingMonitor["requestHeaders"].ToString();
            var h= loggingMonitor["requestHeaders"].ToString();
            // 优先获取 X-Forwarded-For 头部信息携带的IP地址（如nginx代理配置转发）
            var remoteIPv4 = ((JArray)loggingMonitor["requestHeaders"]).OfType<JObject>()
                .FirstOrDefault(header => (string)header["key"] == "X-Forwarded-For")?["value"]?.ToString();
            var browser = "";
            var os = "";
            if (loggingMonitor["userAgent"] != null)
            {
                var client = Parser.GetDefault().Parse(loggingMonitor["userAgent"].ToString());
                browser = $"{client.UA.Family} {client.UA.Major}.{client.UA.Minor} / {client.Device.Family}";
                os = $"{client.OS.Family} {client.OS.Major} {client.OS.Minor}";
            }

            if (string.IsNullOrEmpty(remoteIPv4))
                remoteIPv4 = loggingMonitor["remoteIPv4"].ToString();
            var UserName = loggingMonitor["authorizationClaims"].FirstOrDefault(claim => claim["type"].ToString() == "USERNAME")?["value"]?.ToString();
            var logModel = new SYS_LOG
            {
                USERNAME = UserName,
                ACTIONNAME = loggingMonitor["controllerTypeName"].ToString(),
                BROWSER = browser,
                ACTIONTYPENAME = loggingMonitor["actionTypeName"].ToString(),
                DISPLAYTITLE = loggingMonitor["displayTitle"].ToString(),
                REMOTEIPV4 = remoteIPv4,
                HTTPMETHOD = loggingMonitor["httpMethod"].ToString(),
                TRACEID = loggingMonitor["traceId"].ToString(),
                THREADID = loggingMonitor["threadId"].ToString(),
                REQUESTURL = loggingMonitor["requestUrl"].ToString(),
                TIMEOPERATIME = loggingMonitor["timeOperationElapsedMilliseconds"].ToString(),
                LOGLEVEL = logMsg.LogLevel.ToString(),
                ALLINFO = logMsg.Message,
                CREATE_TIME = DateTime.Now
            };
            _db.Insertable(logModel).ExecuteCommand();
            await Task.Delay(50); // 延迟 0.05 秒写入数据库，有效减少高频写入数据库导致死锁问题
        }
        catch(Exception ee)
        {
            Log.Error(ee.Message);
        }

    }
}

